import { CustomRouterContext } from '@/routes'
import { errorRes } from '@/utils/responseModel'
import { TokenStatus, verifyToken } from '@/utils/token'
import Koa, { ParameterizedContext } from 'koa'
import koaRouter from 'koa-router'

const permission = () => {
    return async (ctx: ParameterizedContext<any, CustomRouterContext & koaRouter.IRouterParamContext<any, CustomRouterContext>, any>, next: Koa.Next) => {
        if (ctx.path.startsWith('/public/')) {
            await next()
        } else {
            const token = ctx.header.authorization
            if (!token) throw new errorRes('Unauthorized')
            await verifyToken(token).then(async r => {
                if (r.tokenStatus === TokenStatus.available) {
                    // @ts-expect-error 初始化，忽略
                    if (!ctx.global) ctx.global = {}
                    ctx.global.tokenInfo = r
                    await next()
                } else {
                    throw new errorRes('Unauthorized')
                }
            })
        }
    }
}

export {
    permission
}